// pages/ap_wifi_input/ap_wifi_input.js
var config = require('../../config.js')
import Dialog from '@vant/weapp/dialog/dialog';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uuid:'',
    wifi_name: '',
    wifi_passwd: '',
    setInter: '',
    setInter_online: '',
    parnetCnt:0,
    is_inputFocus:0,
    token:'',
    wifi_code:0,
    platform:"",
    client: "",
    mode:0
  },


  onClickLeft() {
    // wx.showToast({ title: '点击返回', icon: 'none' });
    wx.navigateBack({ changed: true });
    // Dialog.confirm({
    //   title: '提示',
    //   confirmButtonText:'继续连接',
    //   cancelButtonText:'退出连接',
    //   message: '设备连接过程中，请勿退出该页面',
    // })
    //   .then(() => {
    //     // on confirm
    //   })
    //   .catch(() => {
    //     // on cancel
    //     wx.navigateBack({
    //       delta: 1
    //     })
    //   });
  },

  onInpustWifiName(event)
  {
    //console.log('onInpustWifiName', event.detail)
    this.setData({
      wifi_name: event.detail
    })
  },

  onInpustWifiPwd(event) {
   console.log('onInpustWifiPwd', event.detail)
    this.setData({
      wifi_passwd: event.detail
    })
  },

  onInpustchangeWifiPwd(event) {
    console.log('onInpustchangeWifiPwd', event.detail.value)
    this.setData({
      wifi_passwd: event.detail.value
    })
  },
  // onKeyboardHeightfocus(e) {
  //   console.log('onKeyboardHeightfocus e:', e)
  // },
  // onKeyboardHeightChange(e) {
  //   console.log('onKeyboardHeightChange e:', e)
  //   let { height, duration } = e.detail;
  //   const isShow = height > 0;
  //   console.log('onKeyboardHeightChange', isShow)
  // },

  onConfigWifiInfo()
  {
  //url: 'http://192.168.0.149:8080', //仅为示例，并非真实的接口地址
    // console.log('onConfigWifiInfo:', config.appid)
   
    // console.log('wifi_code:', this.data.wifi_code)
    var qure_online_cnt = 0;
    var _this = this

    wx.showLoading({
      title: '正在配网...',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 50000)

  console.log("wifi_code:", _this.data.wifi_code)
  setTimeout(function () {
    console.log('wifi_name:', _this.data.wifi_name)
    console.log('wifi_passwd:', _this.data.wifi_passwd)
    try {
      wx.setStorageSync('wifi:' + _this.data.wifi_name, _this.data.wifi_passwd)
    } catch (e) { }
    
    // Dialog.confirm({
    //   title: '提示',
    //   confirmButtonText: '确认配网信息',
    //   cancelButtonText: '关闭',
    //   message: '确认WIFI信息是否正确？',
    // })
    //   .then(() => {
    //     // on confirm
       
    //   })
    //   .catch(() => {
    //     // on cancel
       
    //   });
    if ((_this.data.wifi_code == 200) || (_this.data.wifi_code == '200'))
    {
      console.log("adddev1---")
      app.logoutConnect()
      wx.request({
        url: config.url.addDev,
        method: 'POST',
        data: {
          'uuid': _this.data.uuid,
          'phone': config.phone,
          'platform': _this.data.platform,
          'client': config.client,
          'token': '' + _this.data.token,
          'vers': _this.data.vers,
          'mode': _this.data.mode,
        },
        timeout: 4000,
        header: {
          "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
        },
        success(res) {
          console.log(res)
          clearInterval(_this.data.setInter)
          if (res.data.code == 0) {
            // wx.hideLoading()
          
            qure_online_cnt = 0;
           // setTimeout(function () {
           _this.data.setInter_online = setInterval(function () {    
             
              // wx.hideLoading()
              var cur_timestamp = parseInt(new Date().getTime() / 1000)
              wx.request({
                url: config.url.isOnline,
                method: 'POST',
                data: {
                  'uuid': uuid,
                  'timestamp': cur_timestamp,
                   client: config.client,
                },
                // timeout: 1000,
                header: {
                  "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
                },
                success(res) {
                  console.log("cz Online:", res,"type:",type(res.data.data))
                
                  if ((res.data.data >= 0) && (res.data.data < 100)) {
                    clearInterval(_this.data.setInter_online)
                    wx.hideLoading()
                    wx.showToast({
                      title: '成功',
                      icon: 'success',
                      duration: 2000
                    })

                    _this.setData({
                      parnetCnt: 0
                    })
                    app.logoutConnect()
                    app.globalData.uuids.push(dev_uuid)
                    console.log("cz uuids:", app.globalData.uuids)
                    app.globalData.bootStatus = false
                    app.globalData.netStatus = false

                    // app.globalData.MQ.subscribe(dev_uuid, {}, function (err) {
                    //   if (!err) {
                    //     console.log('注册事件成功=>', dev_uuid)
                    //     app.globalData.MQConnectd = true
                    //   }
                    // })
                  
                    setTimeout(function () {
                    //  app.reConnect()
                      wx.reLaunch({
                        url: '../index/index',
                      })

                    }, 1000)
                  }
                  else {
                    console.log("222", err)
                    _this.data.wifi_code = 0
                    app.globalData.netStatus = false
                   
                    qure_online_cnt++;

                    if (qure_online_cnt>5)
                    {
                      wx.hideLoading()
                      wx.showToast({
                        title: '请确认WIFI信息是否正确',
                        icon: 'none',
                        duration: 2000
                      })
                      clearInterval(_this.data.setInter_online)

                    }
                    
                    // setTimeout(function () {
                    // //  app.reConnect()
                    //   wx.reLaunch({
                    //     url: '../index/index',
                    //   })

                    // }, 1000)

                  }


                },
                fail(err) {
                  console.log("3333", err)
                   wx.hideLoading()
                  // wx.showToast({
                  //   title: '配网失败，请重新配网',
                  //   icon: 'none',
                  //   duration: 2000
                  // })
                }
              })

            }, 4000)
            //清除定时器

          }
          else if (res.data.code == -2) {
            wx.hideLoading()
            wx.showToast({
              title: '设备已经被' + res.data.data + "用户绑定",
              icon: 'none',
              duration: 2000
            })
            app.globalData.netStatus = false
            // clearInterval(_this.data.setInter)
            setTimeout(function () {
              
            //  app.reConnect()
              wx.reLaunch({
                url: '../index/index',
              })

            }, 1000)
          }
          else if (res.data.code == -3) {
            wx.hideLoading()
            wx.showToast({
              title: '用户信息不对',
              icon: 'none',
              duration: 2000
            })
          }
          else {
            wx.hideLoading()
            wx.showToast({
              title: '配网数据失败，请重新确认配网',
              icon: 'none',
              duration: 2000
            })
          }


        },
        fail(err) {
          console.log("2222", err)
          // wx.hideLoading()
          // wx.showToast({
          //   title: '配网失败，请重新配网',
          //   icon: 'none',
          //   duration: 2000
          // })
        }

      })
    }
    else
    {
          if (_this.data.token != "") {

            console.log('wx.request:')
            wx.request({
              url: 'http://192.168.5.11:8899',
              method: 'POST',
              dataType: "json",
              header: {
                'content-type': 'application/json' // 默认值
              },
              data: {
                code: '200',
                wifi_name: _this.data.wifi_name,
                wifi_pwd: _this.data.wifi_passwd,
                token: '' + _this.data.token,
                client: '' + config.wifi_ser_client
              },

              timeout: 9000,
              success(res) {
                console.log(res.data)
                // console.log("code:", res.data.code)
                // console.log("data:", res.data.data)
                // console.log("phone:", config.phone)
                // console.log("platform:", res.data.platform)
                // console.log("client:", res.data.client)
                // console.log("mode:", res.data.mode) //1:清空数据添加， -1：正常添加
                var dev_uuid = res.data.data

                if ((res.data.platform == "") || (res.data.platform == "undefine")) {
                  res.data.platform = 'jl'
                }
                if ((res.data.client == "") || (res.data.client == "undefine")) {
                  res.data.client = 'aipai'
                }

                if ((res.data.code == 200) || (res.data.code == "200")) {

                  // setTimeout(function () {

                  //   _this.onFinishWifiInfo(res) 

                  // }, 200)

                  _this.setData({
                    uuid: res.data.data,
                    parnetCnt: 0,
                    wifi_code: res.data.code,
                    platform: res.data.platform,
                    client: res.data.client,
                    mode: res.data.mode,
                  })
                  var uuid = res.data.data
                  app.logoutConnect()
                  
                  _this.data.setInter = setInterval(function () {
                    //要延时执行的代码
                    console.log("adddev0---")
                    wx.request({
                      url: config.url.addDev,
                      method: 'POST',
                      data: {
                        'uuid': uuid,
                        'phone': config.phone,
                        'platform': res.data.platform,
                        'client': config.client,
                        'token': '' + _this.data.token,
                        'vers': res.data.vers,
                        'mode': res.data.mode,
                        'product_type': '' +res.data.product_type,
                      },
                      timeout: 2000,
                      header: {
                        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
                      },
                      success(res) {
                        console.log(res)
                      
                        if (res.data.code == 0) {
                        
                          //app.logoutConnect()
                          clearInterval(_this.data.setInter)

                          qure_online_cnt = 0;
                          // setTimeout(function () {
                        _this.data.setInter_online = setInterval(function () {  
                            // wx.hideLoading()
                            var cur_timestamp = parseInt(new Date().getTime() / 1000)
                            wx.request({
                              url: config.url.isOnline,
                              method: 'POST',
                              data: {
                                'uuid': uuid,
                                'timestamp': cur_timestamp,
                                'client': config.client, 
                              },
                              // timeout: 1000,
                              header: {
                                "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
                              },
                              success(res) {
                             
                                console.log("cz Online:", res)
                                if ((res.data.data >= 0) && (res.data.data < 20))
                                {
                                  clearInterval(_this.data.setInter_online)
                                  wx.hideLoading()
                                  wx.showToast({
                                    title: '成功',
                                    icon: 'success',
                                    duration: 2000
                                  })

                                  _this.setData({
                                    parnetCnt: 0
                                  })
                                  app.logoutConnect()
                                  app.globalData.uuids.push(dev_uuid)
                                  console.log("cz uuids:", app.globalData.uuids)
                                  app.globalData.bootStatus = false
                                  app.globalData.netStatus = false
                                  setTimeout(function () {
                                    // app.reConnect()
                                    wx.reLaunch({
                                      url: '../index/index',
                                    })

                                  }, 1000)
                                }
                                else 
                                {
                                  qure_online_cnt++;

                                  if (qure_online_cnt > 5)
                                  {
                                    clearInterval(_this.data.setInter_online)
                                    wx.hideLoading()

                                    wx.showToast({
                                      title: '请确认WIFI信息是否正确',
                                      icon: 'none',
                                      duration: 2000
                                    })
                                  }
                                   
                                  _this.data.wifi_code = 0
                                
                                  app.globalData.netStatus = false
                                  // setTimeout(function () {
                                  //   // app.reConnect()
                                  //   wx.reLaunch({
                                  //     url: '../index/index',
                                  //   })

                                  // }, 1000)
                                }
                                

                              },
                              fail(err) {
                                console.log("3333", err)
                                // wx.hideLoading()
                                // wx.showToast({
                                //   title: '配网失败，请重新配网',
                                //   icon: 'none',
                                //   duration: 2000
                                // })
                              }
                            })
                            
                          }, 4000)
                          //清除定时器
                          
                        }
                        else if (res.data.code == -2) {
                          wx.hideLoading()
                          wx.showToast({
                            title: '设备已经被' + res.data.data + "用户绑定",
                            icon: 'none',
                            duration: 2000
                          })
                          app.globalData.netStatus = false
                          clearInterval(_this.data.setInter)
                          setTimeout(function () {
                            // app.reConnect()
                            wx.reLaunch({
                              url: '../index/index',
                            })

                          }, 1000)
                        }
                        else if (res.data.code == -3) {
                          wx.hideLoading()
                          clearInterval(_this.data.setInter)
                          wx.showToast({
                            title: '用户信息不对',
                            icon: 'none',
                            duration: 2000
                          })
                        }
                        else {
                          wx.hideLoading()
                          
                          wx.showToast({
                            title: '配网数据失败，请重新确认配网',
                            icon: 'none',
                            duration: 2000
                          })
                        }


                      },
                      fail(err) {
                        console.log("2222", err)
                        // wx.hideLoading()
                        // wx.showToast({
                        //   title: '配网失败，请重新配网',
                        //   icon: 'none',
                        //   duration: 2000
                        // })
                      }

                    })

                  }, 2500) //延迟时间 这里是2秒

                }
                else {
                  console.log("22222222222[", _this.data.parnetCnt);
                  _this.setData({
                    parnetCnt: _this.data.parnetCnt++
                  })
                  if (_this.data.parnetCnt > 5) {
                    //_this.onFinishWifiInfo(res)
                    clearInterval(_this.data.setInter)
                    wx.hideLoading()

                    wx.showToast({
                      title: '配网失败，请重新确认配网',
                      icon: 'none',
                      duration: 2000
                    })
                  }
                }

              },
              fail(e) {
                console.error(e)
                wx.hideLoading()

                wx.showToast({
                  title: '配网失败，请检查是否连接设备热点',
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          }
          else {
            wx.showToast({
              title: '获取用户ID失败',
              icon: 'none',
              duration: 2000
            })
          }

        }
               
  
   
  
  
   
    }, 500)
    
  },

  onFinishWifiInfo(res)
  {
    var _this = this
    console.log('onFinishWifiInfo')

    wx.request({
      url: 'http://192.168.5.11:8899',
      method: 'POST',
      dataType: "json",
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        code: '300',
        wifi_name: _this.data.wifi_name,
        wifi_pwd: _this.data.wifi_passwd,
        token: '' + _this.data.token,
        client: config.wifi_ser_client,
      },
      timeout: 10000,
      success(res) {
        console.log(res.data)
        app.logoutConnect()
        setTimeout(function () {
          //要延时执行的代码
          console.log("adddev2---")
          wx.request({
            url: config.url.addDev,
            method: 'POST',
            data: {
              'uuid': res.data.data,
              'phone': config.phone,
              'platform': res.data.platform,
              'client': config.client,
              'token': '' + _this.data.token,
              'vers': res.data.vers,
            },
            timeout: 5000,
            header: {
              "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
            },
            success(res) {
              console.log(res)
              wx.hideLoading()
              if (res.data.code == 0) {
                wx.showToast({
                  title: '成功',
                  icon: 'success',
                  duration: 2000
                })
                app.globalData.netStatus = false
                clearInterval(_this.data.setInter)
                wx.hideLoading()
                setTimeout(function () {
                  //app.reConnect()
                  wx.reLaunch({
                    url: '../index/index',
                  })

                }, 1000)
              }
              else if (res.data.code == -2) {
                wx.showToast({
                  title: '设备已经存在',
                  icon: 'none',
                  duration: 2000
                })
                app.globalData.netStatus = false
                setTimeout(function () {
                 // app.reConnect()
                  wx.reLaunch({
                    url: '../index/index',
                  })

                }, 1000)
              }
              else if (res.data.code == -3) {
                wx.showToast({
                  title: '用户信息不对',
                  icon: 'none',
                  duration: 2000
                })
              }
              else {
                wx.showToast({
                  title: '配网数据失败，请重新确认配网',
                  icon: 'none',
                  duration: 2000
                })
              }


            },
            fail(err) {
              console.log("22223", err)
              wx.hideLoading()
              wx.showToast({
                title: '配网失败，请重新配网',
                icon: 'none',
                duration: 2000
              })
            }

          })

        }, 2500) //延迟时间 这里是2秒

      },
      fail(e) {
        console.error(e)
        wx.hideLoading()
        app.logoutConnect()
        // wx.showToast({
        //   title: '配网失败，请检查是否连接设备热点',
        //   icon: 'none',
        //   duration: 2000
        // })

        wx.request({
          url: config.url.addDev,
          method: 'POST',
          data: {
            'uuid': res.data.data,
            'phone': config.phone,
            'platform': res.data.platform,
            'client': config.client,
            'token': '' + _this.data.token,
            'vers': res.data.vers,
          },
          timeout: 5000,
          header: {
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
          },
          success(res) {
            console.log(res)
            wx.hideLoading()
            if (res.data.code == 0) {
              wx.showToast({
                title: '成功',
                icon: 'success',
                duration: 2000
              })
              app.globalData.netStatus = false
              setTimeout(function () {
               // app.reConnect()
                wx.reLaunch({
                  url: '../index/index',
                })

              }, 1000)
            }
            else if (res.data.code == -2) {
              wx.showToast({
                title: '设备已经存在',
                icon: 'none',
                duration: 2000
              })
              app.globalData.netStatus = false
              setTimeout(function () {
               // app.reConnect()
                wx.reLaunch({
                  url: '../index/index',
                })

              }, 1000)
            }
            else if (res.data.code == -3) {
              wx.showToast({
                title: '用户信息不对',
                icon: 'none',
                duration: 2000
              })
            }
            else {
              wx.showToast({
                title: '配网数据失败，请重新确认配网',
                icon: 'none',
                duration: 2000
              })
            }


          },
          fail(err) {
            console.log("2222", err)
            wx.hideLoading()
            wx.showToast({
              title: '配网失败，请重新配网',
              icon: 'none',
              duration: 2000
            })
          }

        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("onLoad:", options)
    console.log("token:", options.token)
    try {
      var wifi_passwd = wx.getStorageSync('wifi:' + options.wifi_name)
      console.log("wifi_passwd:", wifi_passwd)
    } catch (e) { }

    this.setData({
      wifi_name: options.wifi_name,
      wifi_passwd: wifi_passwd,
      token: options.token
    })

    //获取对应小程序APPId 对应的token
    
    //var that = this;
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    if(this.data.token == '')
    {
      var token = wx.getStorageSync('token')

      this.setData({
        token: token
      })
    }

    // wx.startWifi({
    //   success(res) {
    //     console.log(res.errMsg)

    //     wx.getConnectedWifi({
    //       success: function (e) {
    //         console.log("wifi e:", e)
    //         if (e.errMsg == "getConnectedWifi:ok") {
    //           var str = e.wifi.SSID
    //           console.log("indexOf:", str.indexOf('AP-'), 'length:', str.length)
    //           if ((str.indexOf('AP-') == 0) && (str.length == 18)) {

    //           }
    //           else {
    //             wx.showToast({
    //               title: '请连接设备热点,再进行配置',
    //               icon: 'none',
    //               duration: 2000
    //             })
    //           }
    //         }
    //       },
    //       fail: function (e) {
    //         console.log("wifi err:", e)
    //       }

    //     })
    //   }
    // })
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.setInter)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  }

  
})